  <template>
    <div class="login-container">
      <div class="login-box">
        <el-form ref="formRef" :rules="data.rules" :model="data.form" class="login-form" destroy-on-close >
          <h2 style="text-align: center; color: #fff; margin-bottom: 30px;color: black">登录</h2>

          <el-form-item prop="username">
            <el-input
                v-model="data.form.username"
                placeholder="用户名"
                prefix-icon="User"
                clearable
            ></el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
                v-model="data.form.password"
                type="password"
                placeholder="密码"
                prefix-icon="Lock"
                show-password
            ></el-input>
          </el-form-item>


          <el-form-item prop="role">
            <el-select
                v-model="data.form.role"
                placeholder="选择角色"
                style="width: 100%"
            >
              <el-option label="管理员" value="ADMIN" />
              <el-option label="评委" value="JUDGE" />
              <el-option label="参赛者" value="PARTICIPANT" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
                type="primary"
                class="login-btn"
                @click="handleLogin"
            >
              登录
            </el-button>

            <el-button
                type="success"
                class="login-btn"
                @click="handleRegister"
            >
              注册
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </template>

  <script setup>
  import {reactive, ref} from "vue";
  import { ElMessage } from 'element-plus';
  import request from "@/utils/request.js";
  import router from "@/router/index.js";

  const data = reactive({
    form: {
      username: '',
      password: '',
      email: '',
      phone: '',
      role: ''
    },
    rules:{
      username:[
        {required: true,message: '请输入姓名',trigger:['blur', 'change']},
        { min: 2, max: 20, message: '用户名长度在2到20个字符之间', trigger: 'blur' }
      ],
      password:[
        {required: true,message: '请输入密码',trigger:['blur', 'change']},
        { min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur' }
      ],
      role:[
        {required: true,message: '请选择角色',trigger:['blur', 'change']},

      ],

  }

  });

  const formRef = ref()


  //登录处理
  const handleLogin = () => {

    // 登录逻辑
    formRef.value.validate(async (valid)=>{
      console.log('验证结果:', valid) // 检查是否为true
      if (valid){
        request.post('/login',data.form).then(res => {
          const code = String(res.code).trim(); // 转为字符串
          if (code == "200"){
            const role = res.data.role; // 使用后端返回的角色[1](@ref)
            localStorage.setItem('user',JSON.stringify(res.data))
            switch(role){
              case 'ADMIN':
                //保存后台返回的用户信息
                localStorage.setItem('admin',JSON.stringify(res.data))//json对象 转 json字符串存储
                  router.push('/Manager/racer');
                ElMessage.success("登录成功");
                break;
              case 'JUDGE':
                localStorage.setItem('judge',JSON.stringify(res.data))//json对象 转 json字符串存储
                  router.push('/adjustIndex/eventApply');
                ElMessage.success("登录成功");
                break;
              case 'PARTICIPANT':
                localStorage.setItem('participant',JSON.stringify(res.data))//json对象 转 json字符串存储
                  router.push('/participantIndex/participantEventPage');
                ElMessage.success("登录成功");
                break;
              default:
                router.push('/CompetitionIndex').catch(err =>{
                  console. error('路由跳转失败:',err);
                })
            }
          }else {
            ElMessage.error(res.msg)
          }
        }).catch(err =>{
          console.log('登录用户:',err.response?.data);
          ElMessage.error(err.response?.data?.msg || '登录失败');
        })
      }
    })



  };


  //注册
  const handleRegister = () => {
    router.push('/registerIndex')
  };
  </script>


  <style scoped>
  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-image: url("@/assets/bg.jpeg");
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
  }

  .login-box {
    background-color: rgba(238, 250, 242, 0.85);
    width: 400px;
    padding: 30px 40px;
    border-radius: 10px;
    box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
  }

  .login-form {
    margin-top: 20px;
  }

  .login-btn {
    width: 48%;
    margin-top: 10px;
  }

  .el-select {
    width: 100%;
  }
  </style>
